/*
 *    Copyright (c) 2006 ThoughtWorks, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.thoughtworks.turtlemock.proxybuilder;

import com.thoughtworks.turtlemock.internal.ProxyBuilder;
import com.thoughtworks.turtlemock.internal.ProxyTypeMock;
import junit.framework.AssertionFailedError;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CglibProxyBuilder implements ProxyBuilder {
    public static final String NET_SF_CGLIB_PROXY_CALLBACK_CLASS_NAME = "net.sf.cglib.proxy.Callback";
    public static final String NET_SF_CGLIB_PROXY_INVOCATION_HANDLER_CLASS_NAME = "net.sf.cglib.proxy.InvocationHandler";
    public static final String NET_SF_CGLIB_PROXY_ENHANCER_CLASS_NAME = "net.sf.cglib.proxy.Enhancer";
    public static final String ENHANCER_CREATE_METHOD_NAME = "create";

    public Object newProxyInstance(Class type, ProxyTypeMock mock) {
        MockInvocationHandler mockInvocationHandler = new MockInvocationHandler(mock);
        try {
            Object[] args = new Object[]{type, createCglibInvocationHandler(mockInvocationHandler)};
            return getEnhancerCreateMethod().invoke(null, args);
        } catch (Exception e) {
            throw new AssertionFailedError("We need cglib to mock class. error: " + e.getMessage());
        }
    }

    private Object createCglibInvocationHandler(final MockInvocationHandler mockInvocationHandler) throws ClassNotFoundException {
        return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{getCglibInvocationHandlerClass()}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return mockInvocationHandler.invoke(args[0], (Method) args[1], (Object[]) args[2]);
            }
        });
    }

    private Method getEnhancerCreateMethod() throws NoSuchMethodException, ClassNotFoundException {
        return getCglibenhancerClass().getDeclaredMethod(ENHANCER_CREATE_METHOD_NAME, new Class[]{Class.class, getCglibCallbackClass()});
    }

    private Class getCglibCallbackClass() throws ClassNotFoundException {
        return Class.forName(NET_SF_CGLIB_PROXY_CALLBACK_CLASS_NAME);
    }

    private Class getCglibenhancerClass() throws ClassNotFoundException {
        return Class.forName(NET_SF_CGLIB_PROXY_ENHANCER_CLASS_NAME);
    }

    private Class getCglibInvocationHandlerClass() throws ClassNotFoundException {
        return Class.forName(NET_SF_CGLIB_PROXY_INVOCATION_HANDLER_CLASS_NAME);
    }

}
